package com.baseframe.auth.service;

import com.baseframe.auth.entity.BaseUserDetails;
import com.baseframe.auth.utils.WrapperUtil;
import com.baseframe.system.entity.BasePermission;
import com.baseframe.system.feign.BaseSystemFeign;
import com.baseframe.tool.container.Kv;
import com.baseframe.tool.result.R;
import com.baseframe.user.entity.BaseUser;
import com.baseframe.user.feign.BaseUseFeign;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户信息认证与授权
 */
@Service
@AllArgsConstructor
public class BaseUserDetailsServiceImpl implements UserDetailsService {

    private  BaseUseFeign baseUseFeign;
    private  BaseSystemFeign baseSystemFeign;

    @Override
    public BaseUserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        R<BaseUser> user2Result = baseUseFeign.findAllByUsername(username);
        BaseUser baseUser = user2Result.getData();
        if (baseUser==null){
            throw  new InternalAuthenticationServiceException("用户名或密码错误~");
        }
        if (baseUser.getStatus()==0){
            throw  new InternalAuthenticationServiceException("当前账号已经已被封禁，无法登录");
        }
        R<List<BasePermission>> permissions2Result = baseSystemFeign.findPermissionListByRoleId(baseUser.getRoleId());
        List<BasePermission> permissions = permissions2Result.getData();
        if (permissions==null||permissions.isEmpty()){
            throw  new InternalAuthenticationServiceException("角色信息不存在或角色无权限~");

        }
        Kv kv = Kv.create();
        return WrapperUtil.buildUserDetails(baseUser,permissions,kv);
    }

}
